package main.java.com.example.demo.innoket.generate;

import main.java.com.example.demo.innoket.vo.Table;
import main.java.com.example.demo.innoket.util.*;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import java.io.StringWriter;
import java.util.List;

/**
 * js 模板
 */
public class JsGenerate implements Generate {
	FileType jsFileType = null;

	public JsGenerate(FileType jsFileType) {
		this.jsFileType = jsFileType;
	}

	@SuppressWarnings("static-access")
	public void generate(Table table, GeneratorConfig.ModulePath path) throws Exception {
		if (jsFileType == null)
			throw new Exception(JsGenerate.class.getName() + ": jsFileType 为null");
		/* get the Template */
		Template t = new VelocityUtil().getTemplate(Resources.TEMPLATE_PATH+"/"+jsFileType.getTemplate());

		VelocityContext context = new VelocityContext();


		//获取实例对象名
		String tableName = table.getTableName().toLowerCase();
		StringBuilder sb = new StringBuilder();
		String[] arrs = tableName.split("_");
		if(arrs!=null && arrs.length>0){
			int len = arrs.length;
			if (len > 1) {
				for (int i = 1; i < len; i++) {
					String s = arrs[i];
					sb.append(Character.toUpperCase(s.charAt(0)));
					sb.append(s.substring(1));
				}
			}
		}
		//前缀
		String model = arrs[0].toLowerCase();
		String entityInstance= ConvertHandler.getEntityInstance(tableName);
		String className = ConvertHandler.table2clazzName(tableName);//entityInstance.substring(0,1).toUpperCase()+entityInstance.substring(1,entityInstance.length());
		context.put("entityName", className);
		context.put("entityInstance", entityInstance);
		context.put("tableName", table.getTableName().toLowerCase());
		context.put("columns", table.getColumns());

		context.put("requestMapping", Resources.TEMPLATE_PATH);
		context.put("moudle", entityInstance);//模块名
		context.put("model", model);//前缀
		context.put("model", model);//前缀
		String tableMemo = table.getPk().getComment();
		context.put("tableMemo", tableMemo);
		String jsFile = new Underline2Camel().camel2Underline(entityInstance).toLowerCase();
		String JsRequertName = jsFile.replaceAll("_", "/");
		String toViewName = jsFile+jsFileType.getFileNameExtension().replace("_list.js", "_view.jsp");
		String toSaveName = jsFile+jsFileType.getFileNameExtension().replace("_list.js", "_add.jsp");
		
		context.put("JsRequertName", JsRequertName);//前缀
		context.put("toViewName", toViewName);//前缀
		context.put("toSaveName", toSaveName);//前缀
		
		StringWriter writer = new StringWriter();
		t.merge(context, writer);
		
//		FileUtil.create(Resources.JS_FILE_PATH +"/"+ Resources.JS_FILE_PACKAGE+ "/" + model +"/", jsFile + jsFileType.getFileNameExtension(), writer.toString());
	}

	public void generate(List<Table> tables,GeneratorConfig.ModulePath path) throws Exception {

	}

}
